package com.easy.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.easy.bean.PermissionBean;
import com.easy.bean.RoleBean;
import com.easy.bean.UserBean;
import com.easy.service.EasyService;

@Component
public class EasyRealm extends AuthorizingRealm {
	@Autowired
	EasyService easyS;

	/**
	 * 认证的方法
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		Object password = token.getCredentials();
		System.out.println(password);
		UserBean user = easyS.getUserByUsername(username);
		// 无账号
		if (user == null) {
			throw new DisabledAccountException();
		}
		// 空密码或密码不正确
		if (password == null || user.getPassword().equals(password)) {
			throw new IncorrectCredentialsException();
		}
		SimpleAuthenticationInfo result = new SimpleAuthenticationInfo(username, password, getName());
		return result;
	}

	/**
	 * 授权的方法
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		List<RoleBean> roles = easyS.getRolesByUserName(username);
		List<PermissionBean> permissions = easyS.getPermissionByUserName(username);
		SimpleAuthorizationInfo result = new SimpleAuthorizationInfo();
		for (RoleBean item : roles)
			result.addRole(item.getName());
		for (PermissionBean item : permissions)
			result.addStringPermission(item.getName());
		return result;
	}

}
